package qdu.szmt.szmt_cont_prov;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;

public class Mydbadpt {
    //***********************************
    private static String DB_NAME = "sm_testdb";
    private static int DB_VEERSION = 1;
    private static  String TB_NAME = "mydata";
    private  static  String KEY_ID = "_id";
    private  static String KEY_MSG = "msg";

    //***********************************
    Context c;
    Mydbhelpr mydbhelpr;
    SQLiteDatabase db;

    Mydbadpt(Context c){
        this.c = c;
    }
    public void opendb(){
        mydbhelpr = new Mydbhelpr(c, DB_NAME, null, DB_VEERSION);
        try {
            db = mydbhelpr.getWritableDatabase();
        }catch(Exception e){
            db = mydbhelpr.getReadableDatabase();
        }
    }
    public void closedb(){
        if(db != null)
            db.close();
        if(mydbhelpr != null)
            mydbhelpr.close();
    }
    public long insertdata(ContentValues cv){
        long newid = -1;
        if(db != null && db.isOpen()){
            newid = db.insert(TB_NAME, null, cv);
        }
        return newid;
    }
    class Mydbhelpr extends SQLiteOpenHelper{

        public Mydbhelpr(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            String sqlstr = "create table " + TB_NAME + " ( " +
                    KEY_ID + " integer primary key autoincrement, " +
                    KEY_MSG + " text not null );";

            if(db != null)
                try {
                    db.execSQL(sqlstr);
                }catch(SQLException E){ E.printStackTrace();}
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

    }
}
